package com.jf3q.front.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jf3q.common.domain.EduComment;
import com.jf3q.common.domain.EduOrder;
import com.jf3q.common.es.entity.CourseEntity;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.vo.ChapterVo;
import com.jf3q.common.vo.CourseWebVo;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.SearchCourseDto;
import com.jf3q.front.service.ChapterService;
import com.jf3q.front.service.CommentService;
import com.jf3q.front.service.CourseService;
import com.jf3q.front.service.OrderService;
import com.jf3q.front.service.es.CourseEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Tag(name = "前台课程controller")
@RequestMapping("/course")
public class CourseController {
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    CourseService courseService;
    @Autowired
    ChapterService chapterService;
    @Autowired
    CourseEntityService courseEntityService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    OrderService orderService;
    @Autowired
    CommentService commentService;

    //根据关键词全文检索-高亮显示
    @GetMapping("/search")
    @Operation(summary = "根据关键词全文检索-高亮显示")
    public ResultVo searchCourses(String keyword,
                                  @RequestParam(defaultValue = "1") Integer number,
                                  @RequestParam(defaultValue = "2")Integer size) {
        Page<CourseEntity> courseEntities = courseEntityService.searchByKeyword(keyword, number, size);
        return setResultMap(size, courseEntities);
    }

    @NotNull
    private ResultVo setResultMap(@RequestParam(defaultValue = "2") Integer size, Page<CourseEntity> courseEntities) {
        Map<String, Object> map = new HashMap<>();
        map.put("items", courseEntities.getContent());
        map.put("current", courseEntities.getNumber()+1);
        map.put("pages", courseEntities.getTotalPages());
        map.put("size", size);
        map.put("total", courseEntities.getTotalElements());
        map.put("hasNext", courseEntities.hasNext());
        map.put("hasPrevious", courseEntities.hasPrevious());

        return  ResultVo.success(map);
    }


    @PostMapping("/search/subject")
    @Operation(summary = "分类查询课程")
    public ResultVo searchBySubject(@RequestBody SearchCourseDto dto,
                                    @RequestParam(defaultValue = "1") Integer number,
                                    @RequestParam(defaultValue = "2")Integer size) {
        //把分页数据获取出来，放到map集合
        Page<CourseEntity> courseEntities = courseEntityService.searchBySubject(dto, number, size);
        return setResultMap(size, courseEntities);
    }

    @Operation(summary = "评论分页列表")
    @GetMapping("/comment/{page}/{limit}")
    public ResultVo getCommentByPage( String courseId, @PathVariable Integer page, @PathVariable Integer limit){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page commentPage=commentService.getPage(courseId, page, limit);

        List commentList = commentPage.getRecords();

        Map map = new HashMap<>();
        return frontPageMap(commentPage, commentList, map);
    }

    @NotNull
    static ResultVo frontPageMap(com.baomidou.mybatisplus.extension.plugins.pagination.Page commentPage, List commentList, Map map) {
        map.put("items", commentList);
        map.put("current", commentPage.getCurrent());
        map.put("pages", commentPage.getPages());
        map.put("size", commentPage.getSize());
        map.put("total", commentPage.getTotal());
        map.put("hasNext", commentPage.hasNext());
        map.put("hasPrevious", commentPage.hasPrevious());
        return ResultVo.success(map);
    }

    //查看是否购买的接口
    @GetMapping("/isBuy/{courseId}")
    public ResultVo isBuy(@PathVariable String courseId, HttpServletRequest request ){
        //根据课程id和用户id查询当前课程是否已经支付过了
        Boolean isBuy=false;
        String token = request.getHeader("token");
        if (StringUtils.checkValNotNull(token)) {
            EduOrder eduOrder = orderService.hasOrderCourse(courseId, jwtTokenUtil.getUserIdByToken(token));
            if (eduOrder!= null && eduOrder.getStatus() ==1) {
                //说明已经支付过了，或者已经报名过了（免费的课）
                isBuy=true;

            }
        }

        return ResultVo.success(isBuy);

    }




    @GetMapping("/{id}")
    public ResultVo getById(@PathVariable String id,HttpServletRequest request){
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(id);
        if (courseWebVo ==null) {
            return ResultVo.error("不存在该课程或者已被删除");
        }

        //根据课程id查询章节和小节
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCourseId(id);
         //增加浏览量自增1
        Long viewCount = redisTemplate.opsForHash().increment("course_" + id, "viewCount", 1);
        Long buyCount = redisTemplate.opsForHash().increment("course_" + id, "buyCount", 0);
        courseWebVo.setViewCount(viewCount);
        courseWebVo.setBuyCount(buyCount);
        Map<String, Object> map = new HashMap<>();
        //根据课程id和用户id查询当前课程是否已经支付过了
        String token = request.getHeader("token");


        map.put("isBuy",false);
        if (StringUtils.checkValNotNull(token)) {
            //有可能token过期
            EduOrder eduOrder = orderService.hasOrderCourse(id, jwtTokenUtil.getUserIdByToken(token));
            if (eduOrder!= null && eduOrder.getStatus() ==1) {
                //说明已经支付过了，或者已经报名过了（免费的课）
                map.put("isBuy",true);

            }
        }

        map.put("courseWebVo",courseWebVo);
        map.put("chapterVideoList",chapterVideoList);

        map.put("chapterVideoList",chapterVideoList);
        return ResultVo.success("",map);
    }
}
